package com.tang.thepath.service;

import android.text.TextUtils;
import android.util.Pair;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;


public class HttpManager {

    private static HttpManager instance = new HttpManager();

    private Retrofit mRetrofit;
    public static final String BASEURL = "http://jcj.m.wcdevelop.com";


    public static HttpManager getInstance(){
        return instance;
    }

    public HttpManager(/*String baseUrl*/) {
        Interceptor tokenInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();
                //Pair<String,String> token=HttpKit.getInstance().getAuthenticator();
                Pair<String,String> token = new Pair<>("Authorization","Bearer "+JWTHolder.getInstance().getToken());
                if (!TextUtils.isEmpty(token.first)&&!TextUtils.isEmpty(token.second)){
                    requestBuilder.header(token.first,token.second);
                }
                requestBuilder.method(original.method(), original.body());
                Response originalResponse = chain.proceed(requestBuilder.build());
                return originalResponse;
            }
        };
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(tokenInterceptor)
                .addInterceptor(new HttpLoggingInterceptor(new FileLogger()).setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASEURL)
                .client(okHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    public Retrofit getRetrofit() {
        return mRetrofit;
    }

    public static <S> S getService(Class<S> serviceClass) {
        return HttpManager.getInstance().getRetrofit().create(serviceClass);
    }
}
